﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PartitionsCodegen
{
    public class G00RapidPositioning : CNCInstruction
    {
        private int posX;
        private int posY;
        private int posZ;

        public G00RapidPositioning(string aLine)
        {
            int index;
            int indexfin;
            index = aLine.IndexOf("X");
            if (index > -1)
            {
                indexfin = aLine.Substring(index).IndexOf(" ");
                posX = Convert.ToInt32(aLine.Substring(index + 1, indexfin));
            }
            index = aLine.IndexOf("Y");
            if (index > -1)
            {
                indexfin = aLine.Substring(index).IndexOf(" ");
                if (indexfin > -1)
                {
                    posY = Convert.ToInt32(aLine.Substring(index + 1, indexfin));
                }
                else 
                {
                    posY = Convert.ToInt32(aLine.Substring(index + 1));
                } 

            }
            index = aLine.IndexOf("Z");
            if (index > -1)
            {
                posZ = Convert.ToInt32(aLine.Substring(index + 1));
            }
        }

        public override void adjustPosition(int ncopy, int size, int z, bool to_the_right) 
        {
            if (to_the_right)
            {
                posX = posX + ncopy * size;
            }
            else
            {
                posY = posY + ncopy * size;
            }

            posZ = z;
        }

        public override String getString()
        {
            String SPosX;
            String SPosY;
            String SPosZ;

            // Only Z value can be omitted (by now)
            if (posX > -1 && posY > -1 && posZ > -1)
            {
                SPosX = posX.ToString();
                SPosY = posY.ToString();
                SPosZ = posZ.ToString();
                return "G00 X" + SPosX + " Y" + SPosY + " Z" + SPosZ;
            }
            else if (posX > -1 && posY > -1)
            {
                SPosX = posX.ToString();
                SPosY = posY.ToString();
                return "G00 X" + SPosX + " Y" + SPosY;
            }
            return null;
        }

        public override int getPosX()
        {
            return posX;
        }

        public override int getPosY()
        {
            return posY;
        }

        public override int getPosZ()
        {
            return posZ;
        }

        public override int getOpCode()
        {
            return 0;
        }
    }
}